package com.eduction.controller;

import com.eduction.bean.EverySchoolCountBean;
import com.eduction.bean.SessionUser;
import com.eduction.common.ReturnCode;
import com.eduction.modules.system.entity.School;
import com.eduction.modules.system.entity.SurveyOpinion;
import com.eduction.modules.target.entity.Detailed;
import com.eduction.modules.target.entity.IndexTargetEntity;
import com.eduction.modules.target.entity.SonTarget;
import com.eduction.resource.BaseController;
import com.eduction.service.*;
import com.eduction.vo.SchoolCountVo;
import com.eduction.vo.SurveyOpinionVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/count")
public class CountController extends BaseController {

    static final Log logger = LogFactory.getLog(CheckController.class);
    @Autowired
    private ExpertGroupMapService expertGroupMapService;
    @Autowired
    private ExpertItemMapService expertItemMapService;
    @Autowired
    private SiteInspectionExpertService siteInspectionExpertService;
    @Autowired
    private IndexTargetEntityService indexTargetEntityService;
    @Autowired
    private SurveyOpinionService surveyOpinionService;
    @Autowired
    private SonTargetService sonTargetService;
    @Autowired
    private DetailedService detailedService;
    @Autowired
    private SurveyProblemService surveyProblemService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    ObservationPointService observationPointService;

    /**
     * 学校成绩汇总总表
     */
    @RequestMapping(value = "/grade/all", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> queryPool(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }
        String pId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        String schoolType = map.get("schoolType");//0-优质学校，1-现代化学校
        String expectType = map.get("expectType");//0-材料评审，1-现场考察
        if (null == pId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        List<School> schoolList = null;
        List<SchoolCountVo> schoolCountVos = new ArrayList<>();
        try {
            //查询所有学校
            schoolList = schoolService.queryBySchoolType(schoolType);
            List<IndexTargetEntity> list1 = indexTargetEntityService.queryAllIndexTarget();
            for (School school : schoolList) {
                SchoolCountVo schoolCountVo = new SchoolCountVo();
                String schoolId = school.getP_id();
                List<SurveyOpinion> ls = new ArrayList<>();
                List<SurveyOpinionVo> voList = new ArrayList<>();
                //List<SurveyOpinion> list = surveyOpinionService.queryAllSurveyOpinion(schoolId,mode);
                if (list1 == null)
                    return toResponse(null, ReturnCode.FAIL, "暂无数据");
                for (int i = 0; i < list1.size(); i++) {
                    List<SonTarget> list2 = sonTargetService.querySonTargetByFid(list1.get(i).getP_id());
                    if (list2 == null) {
                        return toResponse(null, ReturnCode.FAIL, "二级指标不存在!");
                    }
                    for (int j = 0; j < list2.size(); j++) {
                        List<Detailed> list3 = detailedService.queryDetailedByFid(list2.get(j).getP_id(), schoolType);
                        if (list3 == null) {
                            return toResponse(null, ReturnCode.FAIL, "细则不存在!");
                        }
                        for (int k = 0; k < list3.size(); k++) {
                            SurveyOpinion lt = surveyOpinionService.querySurveyOpinionInfo(list3.get(k).getP_id(), schoolId, expectType);
                            SurveyOpinionVo vo = new SurveyOpinionVo();
                            if (lt != null) {
                                BeanUtils.copyProperties(lt, vo);
                            }
                            vo.setTitle((i + 1) + "." + (j + 1) + "." + (k + 1));
                            //ls.add(lt);
                            voList.add(vo);
                        }
                    }
                }
                schoolCountVo.setSchoolId(schoolId);
                schoolCountVo.setVoList(voList);
                schoolCountVos.add(schoolCountVo);
            }
            return toResponse(schoolCountVos, ReturnCode.SUCCESS, "查询汇总表成功");
        } catch (SQLException e) {
            logger.error(e);
            return toResponse(null, ReturnCode.FAIL, "查询汇总表失败!");
        }

    }

    /**
     * 学校成绩汇总总表
     */
    @RequestMapping(value = "/grade/school", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> queryGradeSchool(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }

        String pId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
        String schoolId = map.get("schoolId");//学校编号
        String expectType = map.get("expectType");//0-材料评审，1-现场考察
        if (null == pId) {
            return toResponse(null, ReturnCode.FAIL, "未登录!");
        }
        try{
//        School school = null;
            School school = schoolService.queryById(schoolId);
        List<SurveyOpinionVo> voList=getCount(school,expectType);
            return toResponse(voList, ReturnCode.SUCCESS, "查询汇总表成功");
        } catch (Exception e) {
            logger.error(e);
            return toResponse(null, ReturnCode.FAIL, "查询汇总表失败!");
        }

    }


    /**
     * 查询本年所有学校
     */
    @RequestMapping(value = "/queryScoreByYear" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> querySchoolByPage(HttpServletRequest request,@RequestBody Map<String ,String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
//        if(StringUtils.isEmpty(user_type)){
//            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
//        }

        String expectType = map.get("expectType");//0-材料评审，1-现场考察
        if(StringUtils.isBlank(expectType)){
            expectType="0";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date = new Date();
        String year=sdf.format(date);
        try {
            List<School> schoolList= schoolService.querySchoolByYear(year);
            List<EverySchoolCountBean> beans=new ArrayList<>();
            for(School s:schoolList){
                EverySchoolCountBean bean=new EverySchoolCountBean();
                bean.setSchoolId(s.getP_id());
                bean.setSchoolName(s.getS_name());
                List<SurveyOpinionVo> voList=getCount(s,expectType);
                int a=0;
                int b=0;
                int c=0;
                String optionB=null;
                String optionC=null;
                List<String> opinionBs=new ArrayList<>();
                List<String> opinionCs=new ArrayList<>();

                for(SurveyOpinionVo vo:voList){
                    if("A".equals(vo.getS_key())){
                        a++;
                    }
                    if("B".equals(vo.getS_key())){
                        b++;
                        if(!StringUtils.isBlank(vo.getS_value())){
                            optionB=vo.getTitle()+" "+vo.getS_value();
                        }else{
                            optionB=vo.getTitle()+" 无;";
                        }
                        opinionBs.add(optionB);

                    }
                    if("C".equals(vo.getS_key())){
                        c++;
                        if(!StringUtils.isBlank(vo.getS_value())){
                            optionC=vo.getTitle()+" "+vo.getS_value();
                        }else{
                            optionC=vo.getTitle()+" 无";
                        }
                        opinionCs.add(optionC);
                    }

                }
                String scoreNeed="";
                if(a!=0){
                    scoreNeed=scoreNeed+a+"A";
                }
                if(b!=0){
                    scoreNeed=scoreNeed+b+"B";
                }
                if(c!=0){
                    scoreNeed=scoreNeed+c+"C";
                }

                bean.setAllScore(scoreNeed);
                bean.setOpinionB(opinionBs);
                bean.setOpinionC(opinionCs);
                beans.add(bean);
            }
            return toResponse(beans, ReturnCode.SUCCESS, "查询成功!");
        } catch (SQLException e) {
            logger.error(e);
            return toResponse(null, ReturnCode.SUCCESS, "查询失败!");
        }
    }

    public List<SurveyOpinionVo> getCount(School school,String expectType) {
        try {
            //单个

            String schoolType = school.getP_type_id();

            List<IndexTargetEntity> list1 = indexTargetEntityService.queryAllIndexTarget();
            SchoolCountVo schoolCountVo = new SchoolCountVo();
            List<SurveyOpinion> ls = new ArrayList<>();
            List<SurveyOpinionVo> voList = new ArrayList<>();
            //List<SurveyOpinion> list = surveyOpinionService.queryAllSurveyOpinion(schoolId,mode);
            if (list1 == null)
//                return toResponse(null, ReturnCode.FAIL, "暂无数据");
             logger.info("暂无数据");
            for (int i = 0; i < list1.size(); i++) {
                List<SonTarget> list2 = sonTargetService.querySonTargetByFid(list1.get(i).getP_id());
                if (list2 == null) {
//                    return toResponse(null, ReturnCode.FAIL, "二级指标不存在!");
                    logger.info("二级指标不存在!");
                }
                for (int j = 0; j < list2.size(); j++) {
                    List<Detailed> list3 = detailedService.queryDetailedByFid(list2.get(j).getP_id(), schoolType);
                    if (list3 == null) {
//                        return toResponse(null, ReturnCode.FAIL, "细则不存在!");
                        logger.info("细则不存在!");
                    }
                    for (int k = 0; k < list3.size(); k++) {
                        SurveyOpinion lt = surveyOpinionService.querySurveyOpinionInfo(list3.get(k).getP_id(), school.getP_id(), expectType);
                        SurveyOpinionVo vo = new SurveyOpinionVo();
                        if (lt != null) {
                            BeanUtils.copyProperties(lt, vo);
                        }
                        vo.setTitle((i + 1) + "." + (j + 1) + "." + (k + 1));
                        //ls.add(lt);
                        voList.add(vo);
                    }
                }
            }
            return voList;
        } catch (Exception e) {

            e.printStackTrace();
            logger.info("查询出错");
            return null;
        }

    }

}
